package com.atguigu.yygh.user.controller;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/9/8 7:12 上午
 * @desc
 */
@Api(tags = "用户登陆")
@RestController
@RequestMapping("/api/user")
public class UserInfoApiController {


    private final UserInfoService userInfoService;

    public UserInfoApiController(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo) {
        // 校验验证码
        boolean isChecked = userInfoService.checkCode(loginVo.getPhone(), loginVo.getCode());
        if (isChecked) {
            Map<String, Object> info = userInfoService.userLogin(loginVo);
            return R.ok().data(info);
        } else {
            return R.error().message("验证码错误");
        }
    }


    @ApiOperation("获取用户信息")
    @GetMapping("auth/getUserInfo")
    public R getUserInfo(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("token");
        UserInfo userInfo = userInfoService.getById(JwtHelper.getUserId(token));
        return R.ok().data("userInfo", userInfo);
    }

    @ApiOperation("上传实名认证信息")
    @PostMapping("auth/userAuth")
    public R userAuth(@RequestBody UserAuthVo userAuthVo, HttpServletRequest request) {
        // 从请求头中获取token,并提取id
        Long userId = JwtHelper.getUserId(request.getHeader("token"));
        userInfoService.userAuth(userId, userAuthVo);
        return R.ok();
    }
}